/*

BlackRabbit - OpenSource IDE.
@author Edward Sarkisyan (edward.sarkisyan@gmail.com)
Use LGPL (http://www.gnu.org/copyleft/lesser.html)

*/

#include "projecttreewidget.h"
#include "../classes/projectitem.h"
#include "../classes/projecttreewidgetitem.h"
#include "../dialogs/newfiledialog.h"
#include <QXmlStreamReader>
#include <QFile>
#include <QMessageBox>
#include <QFileInfo>
#include "../globals.h"


#define TYPE 1
#define DESCRIPTION 2
#define PATH 3

#define t_FILE 1
#define t_FOLDER 2
#define t_UNKNOWN 3

ProjectTreeWidget::ProjectTreeWidget(QWidget *parent, QString fileName) :
    QWidget(parent),
    m_ui(new Ui::ProjectTreeWidget)
{
    m_ui->setupUi(this);
    if(!fileName.isEmpty())
        setProjectFile(fileName);
    m_tabsContainer = 0;
}

void ProjectTreeWidget::setProjectFile(QString fileName)
{
    QString filePathes = QFileInfo(fileName).path();
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::critical(0, QString("Error in opening project file"), file.errorString());
    }
    if(file.isReadable())
    {
        ProjectItem *item = new ProjectItem(m_tabsContainer);
        QTreeWidgetItem *curr = new QTreeWidgetItem(0);
        item->setTopLevelitem(curr);
        QXmlStreamReader reader(file.readAll());
        QFileInfo fInfo(file);
        QString currPath = fInfo.absolutePath();
        QString folderPath = QString();
        bool weHaveProjectLanguageExtentionInCollection = false;
        while(!reader.atEnd())
        {
            reader.readNext();
            if(reader.name().compare("name")==0)
            {
                item->topLevelItem()->setText(0,reader.readElementText());
                item->topLevelItem()->setText(1,fInfo.absoluteFilePath());
                item->topLevelItem()->setText(2,"Project");
                item->topLevelItem()->setText(3,"Project description");
            }
            else if(reader.name().compare("language") ==0)
            {
                QString lang = reader.readElementText();
                QVectorIterator<Language*> iteration(*languages);
                QString extLang;
                while(iteration.hasNext())
                {
                    Language* tmp = iteration.next();
                    extLang = tmp->name();
                    if( extLang.contains(lang, Qt::CaseInsensitive))
                    {
                        QMessageBox::information(this, tr("Get project language"), tr("Language: %1").arg(lang));
                        weHaveProjectLanguageExtentionInCollection = true;
                        item->setLanguage(tmp);
                    }
                }
                if(!weHaveProjectLanguageExtentionInCollection)
                    QMessageBox::warning(this, tr("Undefined project type"), tr("Language: %1 Project language: %2").arg(lang, extLang));
            }
            else if(reader.name().compare("author")==0)
            {
                //m_name = reader.readElementText();
            }
            else if(reader.name().compare("file")==0 && curr!=0)
            {
                qDebug("file");
                QString data = filePathes + folderPath.append("/").append(reader.readElementText());
                QString ref = QFileInfo(data).fileName();
                QStringList info;
                info<<ref<<data<<"file";
                qDebug(data.toStdString().c_str());
                curr->addChild(new ProjectTreeWidgetItem(curr, item, info, t_FILE));
            }
            else if(reader.name().compare("folder") ==0)
            {
                if(reader.isStartElement())
                {
                    folderPath.append("/").append(reader.attributes().value("name").toString());
                    QStringList info= QStringList(reader.attributes().value("name").toString());
                    info<<currPath
                        <<"Folder"
                        <<"Folder description";
                    QTreeWidgetItem *fld = new QTreeWidgetItem(curr,info);
                    if(curr!=0)
                    {
                        curr->addChild(fld); // <-- ERROR HERE
                        curr = fld;
                        currPath += "/";
                        currPath += reader.attributes().value("name").toString();
                    }
                    else
                        delete fld;
                }
                else
                {
                    curr = curr->parent();
                    int beg = currPath.lastIndexOf("/");
                    currPath.remove(beg, currPath.size()-beg);
                    folderPath = QString();
                }
            }

        }
        m_ui->treeWidget->insertTopLevelItem(0,item->topLevelItem());
    }
    else
        qDebug("Error@:(");
}

ProjectTreeWidget::~ProjectTreeWidget()
{
    delete m_ui;
}

void ProjectTreeWidget::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void ProjectTreeWidget::on_treeWidget_itemDoubleClicked(QTreeWidgetItem* item, int column)
{
    Q_UNUSED(column);
    if(item->data(2, 0).toString().compare("Project", Qt::CaseInsensitive) != 0
        &&
        (item->data(2, 0).toString().compare("Folder", Qt::CaseInsensitive) != 0))
    {
        (dynamic_cast<ProjectTreeWidgetItem*>(item))->childOf()->openFile(item->data(1, 0).toString());
    }

}

void ProjectTreeWidget::on_newFileButton_clicked()
{
    NewFileDialog *dialog = new NewFileDialog(this);
    dialog->exec();
    delete dialog;
}

void ProjectTreeWidget::on_addFileBttn_clicked()
{
    NewFileDialog *fileDlg = new NewFileDialog(this);
    fileDlg->exec();
    QString fileName = fileDlg->getFileName();
    if(!fileName.isEmpty())
        addNewTo(m_ui->treeWidget->currentItem(),fileName);
}

void ProjectTreeWidget::addNewTo(QTreeWidgetItem *parent, QString fileName)
{
    if(parent!=0)
        if(fileName.isEmpty())
        {
            QMessageBox::critical(this, tr("Wrong filename"), tr("Error: Trying add file whis an empty name"));
            return;
        }
        else
        {
            parent->addChild(new QTreeWidgetItem(parent,QStringList(fileName)));
        }
    else
    {
        m_ui->addFileBttn->setEnabled(false);
        m_ui->removeFileBttn->setEnabled(false);
        m_ui->newFileButton->setEnabled(false);
    }
}


QTreeWidget* ProjectTreeWidget::treeWidget()
{
    return m_ui->treeWidget;
}

bool ProjectTreeWidget::setTabsContainer(QTabWidget* container)
{
    if(m_tabsContainer == 0)
    {
        m_tabsContainer = container;
        return true;
    }
    return false;
}
